package com.xiaomi.controller;

import com.alibaba.fastjson.JSON;
import com.xiaomi.entity.User;
import com.xiaomi.model.Result;
import com.xiaomi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @ClassName UserController
 * @Description UserController
 * @Author lll
 * @Date 2021/11/28 13:32
 * @Version 1.0
 **/
@Controller
@RequestMapping(value = "/User", produces  = "text/json;charset=UTF-8")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/pageSearch.do")
    @ResponseBody
    public String pageSearch(@RequestParam Integer page,
                             @RequestParam Integer limit,
                             @RequestParam(required = false) Integer id,
                             @RequestParam(required = false) String name) {

        Integer startRow = (page - 1) * limit;
        Integer count = userService.getCount(id, name);
        List<User> users = userService.pageSearch(startRow, limit, id, name);
        Result result = new Result();
        result.setCode(0);
        result.setCount(count);
        result.setData(users);
        String s = JSON.toJSONString(result);
        return s;
    }

    @PostMapping("/insert.do")
    @ResponseBody
    public String insert(@RequestParam String zhanghao,
                         @RequestParam String name,
                         @RequestParam String phone,
                         @RequestParam String userpwd,
                         @RequestParam Integer dizhiId,
                         @RequestParam Integer carId) {

        userService.insert(zhanghao, name, phone, userpwd, dizhiId, carId);
        Result result = new Result();
        result.setCode(0);

        String s = JSON.toJSONString(result);
        return s;
    }

    @PostMapping ("/update.do")
    @ResponseBody
    public String update(@RequestParam String zhanghao,
                         @RequestParam String name,
                         @RequestParam String phone,
                         @RequestParam String userpwd,
                         @RequestParam Integer dizhiId,
                         @RequestParam Integer carId,
                         @RequestParam Integer id) {
        userService.update(zhanghao, name, phone, userpwd, dizhiId, carId, id);
        Result result = new Result();
        result.setCode(0);

        String s = JSON.toJSONString(result);
        return s;
    }

    @PostMapping ("/delete.do")
    @ResponseBody
    public String delete(@RequestParam Integer id) {

        userService.delete(id);
        Result result = new Result();
        result.setCode(0);

        String s = JSON.toJSONString(result);
        return s;
    }
}
